# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config

from action.base import jsonAction

'''
Ajax base controller: used for producing views for embedded clients.
'''
class ajaxAction(jsonAction):
    def __init__(self, name=config.NAME):
        jsonAction.__init__(self, name)
        self.name = name
        self.tmplDir = os.path.join(config.TMPL_DIR, 'ajax', config.AJAX_TEMPLATE)
        self.render = web.template.render(self.tmplDir, globals=self.globalsTmplFuncs)
        self.privData['render'] = self.render
        self.privData['PHONEGAP'] = 0
        self.globalsTmplFuncs['makeView'] = self.makeView
        self.globalsTmplFuncs['makeJs'] = self.makeJs
        self.globalsTmplFuncs['makeCss'] = self.makeCss

        if not self.isInstalled():
            raise web.seeother(self.makeUrl('/admin/install'))

    def makeView(self, view, params={}):
        import urllib
        paramsStr = '?'+ urllib.urlencode(params) if len(params)>0 else ''
        return config.WEB_URL + "/ajax/views/" + view + paramsStr

    def makeJs(self, js):
        return config.WEB_URL + "/static/ajax/" + config.AJAX_TEMPLATE + "/" + js

    def makeCss(self, css):
        return config.WEB_URL + "/static/styles/" + config.AJAX_TEMPLATE + "/" + css

    def exportView(self, view, params={}):
        import urllib
        paramsStr = '?'+ urllib.urlencode(params) if len(params)>0 else ''
        return "./%s.html" % view + paramsStr

    def beginExport(self):
        config.WEB_URL = "."
        self.globalsTmplFuncs['makeView'] = self.exportView
        self.privData['PHONEGAP'] = 1

    def endExport(self):
        config.WEB_URL = ""
        self.globalsTmplFuncs['makeView'] = self.makeView
        self.privData['PHONEGAP'] = 0
